﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace SLCommon
{
    public class ObjPoolBase<T> where T:IPoolItem,new()
    {
        protected List<T> doingPool = new List<T>();
        protected List<T> cache = new List<T>();

        protected int capacity = 50;
        protected int expandCount = 25;
        //public ObjPoolBase()
        //{

        //}

        public void InitPool( int capacity,int expandCount) {
            this.capacity = capacity;
            this.expandCount = expandCount;
            Expand(capacity);
        }

        public T GetItem()
        {
            T item = default(T);
            if (cache.Count == 0) 
            {
                Expand(expandCount);
            }

            item = cache[cache.Count - 1];
            cache.RemoveAt(cache.Count - 1);
            item.SetEnable(true);
            return item;
        }

        protected virtual T CreateItem()
        {
            return new T();
        }

        public void RecycleItem(T item)
        {
            doingPool.Remove(item);
            cache.Add(item);
            item.SetEnable(false);
        }

        private void Expand(int count)
        {
            for (int i = 0; i < count; i++)
            {
                T item = CreateItem();
                item.Init();
                item.SetEnable(false);
                cache.Add(item);
            }
        }

        private void Release()
        {
            if (cache.Count>capacity)
            {
                for (int i = capacity-1; i > cache.Count-1; i--)
                {
                    cache.RemoveAt(i);
                }
            }
        }
    }
}
